package com.factory.rest.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.factory.common.bean.User;
import com.factory.common.bean.UserWx;
import com.factory.common.constant.UserConstant;
import com.factory.common.core.BaseServiceImpl;
import com.factory.common.mapper.MenusMapper;
import com.factory.common.mapper.UserMapper;
import com.factory.common.mapper.UserWxMapper;
import com.factory.common.pojo.MenusPojo;
import com.factory.common.pojo.Result;
import com.factory.common.utils.StringUtil;
import com.factory.rest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

	@Autowired
	private UserMapper userMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MenusMapper menusMapper;

    @Autowired
    private UserWxMapper userWxMapper;

    @Override
    protected BaseMapper<User> getBaseMapper() {
        return this.userMapper;
    }

    @Override
    public Result login(String name, String pass) {
        try {
            //编码
            String encode = DigestUtils.md5DigestAsHex(pass.getBytes());
            User user = userMapper.queryByAccount(name);
            if (null == user) {
                return Result.fail("用户不存在");
            }

            if (encode.equalsIgnoreCase(user.getPassword())) {
                return Result.success(setSession(user), "登录成功");
            } else {
                return Result.fail("密码不正确");
            }

        } catch (Exception e) {
            log.error("{}", e);
        }
        return Result.fail("服务异常");
    }

    public JSONObject setSession(User user){
        String token = StringUtil.getUUID();
        request.getSession().setAttribute(UserConstant.getToken(token), user);
        JSONObject json = new JSONObject();
        json.put("token", token);
        json.put("user", user);
        return json;
    }

    @Override
    public Result loginOut() {

        String token = request.getHeader(UserConstant.USERTOKEN);
        if(StringUtil.notEmpty(token)){
            request.getSession().removeAttribute(UserConstant.getToken(token));
        }

        return Result.success(null,"退出登录成功!");
    }

    @Override
    public Optional<User> getLoginUser() {
        String token = request.getHeader(UserConstant.USERTOKEN);
        if (StringUtil.notEmpty(token)) {
            Object o = request.getSession().getAttribute(UserConstant.getToken(token));
            if (null != o) {
                return Optional.of((User) o);
            }
        }
        return Optional.empty();
    }


    @Transactional()
    @Override
    public List<MenusPojo> queryUserMenus(String userId) {
        List<MenusPojo> menus = menusMapper.queryByUser(userId, null);

        menus.forEach(menu -> {
            List<MenusPojo> menusPojos = menusMapper.queryByUser(userId, menu.getId());
            if (menusPojos.size() > 0) {
                menu.setChildren(menusPojos);
            }
        });

        return menus;
    }

    @Override
    public User queryByOpenId(String openId) {
        return userMapper.queryByOpenId(openId);
    }

    @Override
    public Integer insertWx(UserWx userWx) {
        return userWxMapper.insert(userWx);
    }

}
